

class Money implements Cloneable{
    public double money=19.9;

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

class  Person implements Cloneable{  //想调用clone方法必须实Cloneable接口
    public String name;
    public int age;
    public Money m;

    public Person(String name,int age) {
        this.name=name;
        this.age=age;
        this.m=new Money();
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", m=" + m.money +
                '}';
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        Person temp = (Person) super.clone();
        temp.m= (Money) this.m.clone();
        return temp;
    }
}


public class CLone {                        //想调用clone还需要对其进行捕获声明抛出异常
    public static void main(String[] args) throws CloneNotSupportedException {
        Person person1 = new Person("小张",18);
        Person person2 = (Person) person1.clone();
        System.out.println(person1);
        System.out.println(person2);

        System.out.println("=====================");
        person1.m.money=1999.0;
        //如果拷贝的对象中的变量所含有引用的对象，则要进行深拷贝，则需要将为所对象中那个引用的对象也实现Cloneable接口并实现方法
        System.out.println(person1);
        System.out.println(person2);
    }
}
